<?php
namespace app\admin\server\menu;
use think\Request;
use app\admin\ServerBase;
use think\exception\ValidateException;
use think\config;
use app\admin\common;
use app\admin\model\menu\Menu as menuModel;
use app\admin\model\menu\MenuPermission as PermissionModel;
use app\admin\model\role\RolePermission as RolePermissionModel;
use think\facade\Db;
use think\facade\Session;
class Menu extends ServerBase{
	protected $request;
	protected static $model;
	protected $assign_data = [
        'role_id'  =>  'require|number',
        'menu_id'=>'require|array'
    ];
    
    protected $role_id=[
    	'role_id'=>'require|number',
    ];
    
    protected $assign_data_message=[
    	'role_id.require'=>'角色ID不能为空',
    	'role_id.number'=>'角色ID只能为数字',
    	'menu_id.require'=>'菜 单Id不能为空',
    	'menu_id.array'=>'菜单id传过来应该是一个数组'
    ];
    
    public function __construct(Request $request)
    {
    	$this->checkAuth();
        $this->request = $request;
        self::$model=new menuModel();
    }
    
    /**
     * 获取所有菜 单的权限
     * 
     */
    public function getAllMenuPermission(){
    	$menuTag=self::$model->selectMenu(['status'=>1],'*','id asc');
    	return $menuTag;
    	/*
    	$menuPermissionObj=new PermissionModel();
    	$data=$menuPermissionObj->selectMenuPermission(['status'=>1],'id,name,menu_id,type');
    	return $data;
    	*/
    }
    /**
     * 查找角色拥有的菜单
     * 
     */
    public function selectRoleMenu1($roles_id=0){
    	$param=$this->request->param();
    	if($roles_id!=0){
    		$param['role_id']=$roles_id;
    	}
    	try{
			$this->validate($param,$this->role_id,$this->assign_data_message);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            $this->getMessageCode('adminMessage.field.error',1);
            $this->error=$this->error.','.$e->getError();
            return false;
        }
        $rolePermissionObj=new RolePermissionModel();
        $where=[
        	'p.status'=>1,
        	'p.role_id'=>$param['role_id']
        ];
        //菜单权限
        $menuTag=$this->getAllMenuPermission();
        //角色拥有的菜单
        $menu=$rolePermissionObj->selectRoleMenuPermission($where);
        //2.查找用户所拥有的菜单
        if(!$menu){
        	$this->getMessageCode('adminMessage.permission.select_permission',1);
        	return false;
        }
        $menu=common::combination($menu,$menuTag);
    	$data=common::formatList($menu);
    	$this->getMessageCode('adminMessage.success.select',2);
    	return $data;
    }
    
    public function checkAssignRoleMenu($data){
    	$data_insert=[];
    	foreach($data['perm'] as $k=>$v){
    		$data_insert[$k]['menu_id']=$v;
    		$data_insert[$k]['menu_permission']='';
    		$data_insert[$k]['create_time']=time();
    		$data_insert[$k]['role_id']=trim($data['id']);
    		$data_insert[$k]['status']=1;
    	}
    	return ['data_insert'=>$data_insert];
    }
    
    public function getUserLeftMenu(){
    	$_admin=$this->getAdmin();
		$roles_id=$_admin['roles_id'];
		$department_id=$_admin['department_id'];
		//1管理员 //0普通员工
		if($roles_id==1){
			$_user_menu=$this->getAdminMenu();
		}else{
			$_user_menu=$this->getUserMenu($department_id);
		}
		
		$menu=common::combination($_user_menu,[]);
    	//组合菜单
    	$data=common::formatList($menu);
    	$this->getMessageCode('adminMessage.success.select',2);
    	return $data;
    }
    /**
     * @Purpose 获取岗位菜单及用户的菜单
     */
    public function selectRoleMenu(){
    	$_param=$this->request->param();
    	$_id=$_param['id'];
    	//1.获取用户所拥有的菜单
    	$_admin=$this->getAdmin();
		$roles_id=$_admin['roles_id'];
		$department_id=$_admin['department_id'];
		//1管理员 //0普通员工
		if($roles_id==1){
			$_user_menu=$this->getAdminMenu();
		}else{
			$_user_menu=$this->getUserMenu($department_id);
		}
    	//2.获取岗位所拥有的菜单
    	$_job_menu=$this->getJobMenu($_id);
    	//组合菜单
    	$data=common::formatListNew($_user_menu,$_job_menu);
    	$this->getMessageCode('adminMessage.success.select',2);
    	return $data;
    }
    
    //获取当前岗位所拥有的菜单
    public function getJobMenu($_id){
    	$rolePermissionObj=new RolePermissionModel();
        $where=[
        	'p.status'=>1,
        	'p.role_id'=>$_id
        ];
        //菜单权限
        $menuTag=$this->getAllMenuPermission();
        //角色拥有的菜单
        $menu=$rolePermissionObj->selectRoleMenuPermission($where);
        return $menu;
    }
    
    //获取管理员的菜单
    public function getAdminMenu(){
    	$where=[
    		'status'=>1
    	];
    	$order="displayorder asc";
    	$menu=self::$model->selectMenu($where,'function,id,status,pid,menu_name,displayorder,type',$order);
    	//var_dump($menu,self::$model->getLastSql());exit;
    	$menuTag=self::$model->selectMenu(['status'=>1],'*','id asc');
    	
    	$menu=common::combination($menu,$menuTag);
    	return $menu;
    }
    
    //如果是普通用户获取当前用户的职位的菜单
    public function getUserMenu($_id){
    	$rolePermissionObj=new RolePermissionModel();
        $where=[
        	'p.status'=>1,
        	'p.role_id'=>$_id
        ];
        //菜单权限
        $menuTag=$this->getAllMenuPermission();
        //角色拥有的菜单
        $menu=$rolePermissionObj->selectRoleMenuPermission($where);
        return $menu;
    }
	/**
	 * 给角色分配菜单
	 * 
	 */
    public function assignRolesMenu(){
    	$param=$this->request->param();
        $menu=$this->checkAssignRoleMenu($param);
        extract($menu);
        $obj=new RolePermissionModel();
        //1.把该 用户以前角色的所有菜单权限给设置为不可用
        $obj->update(['status'=>0],['role_id'=>$param['id']]);
        //2查找该角色是否拥有权限，如果拥有 则更新
        $role_permission_flag=$obj->selectMenuPermission(['role_id'=>$param['id']],'id,role_id,menu_id');
        
        if(!empty($role_permission_flag) && isset($role_permission_flag)){
        	$result=true;
        	Db::startTrans();
        	foreach($data_insert as $k=>$v){
        		$flag=0;
        		foreach($role_permission_flag as $kk=>$vv){
        			if($v['menu_id']==$vv['menu_id']){//更新
        				$flag=1;
        				$r=$obj->db_update($v,$where=['id'=>$vv['id']]);
        				if(!$r){
        					Db::rollback();
        					$result=false;break;
        				}
        			}
        		}
        		//如果该数据没有存储过 新添加
        		if($flag==0){
        			$r=$obj->db_insert($v);
        			if(!$r){
        				Db::rollback();
        				$result=false;break;
        			}
        		}
        	}
        	Db::commit();
        }else{//如果是第一次给角色添加权限 则直的插入
        	$result=$obj->insertAll($data_insert);
        }
        if($result==false){
        	$this->getMessageCode('adminMessage.permission.add_permission.error',1);
        	return false;
        }
        $this->getMessageCode('adminMessage.permission.add_permission.success',2);
        return true;
    }
    
    /**
     * 查找当前系统功能菜单
     * 
     */
    public function select(){
    	$param=$this->request->param();
    	$where=[
    		'status'=>1,
    		'type'=>0,
    	];
    	$order="displayorder asc";
    	$menu=self::$model->selectMenu($where,'function,id,status,pid,menu_name,displayorder,type',$order);
    	
    	$menuPermission=new PermissionModel();
    	$menuTag=self::$model->selectMenu(['status'=>1],'*','id asc');
    	
    	$menu=common::combination($menu,$menuTag);
    	$data=common::formatList($menu);
    	$this->getMessageCode('adminMessage.success.select',2);
    	return $data;
    }

 	public function combination_menu(){
 		$Session=Session::all();
		$roles_id=$Session['roles_id'];
		$rolePermissionObj=new RolePermissionModel();
		$order="displayorder asc";
		$roles_id=$Session['roles_id'];
		if(stripos($roles_id,',')){
			$roles_data=explode(',',$roles_id);
		}else{
			$roles_data[]=$roles_id;
		}
		if(!in_array(1,$roles_data)){
			$where[]=array(
				'p.status',"=",1
			);
			$where[]=array(
				'p.role_id',"=",$roles_id
			);
			 $manager_menu=$rolePermissionObj->selectRoleMenuPermission($where);
			
		}else{//管理员
			$manager_menu=self::$model->selectMenu(["status"=>1],'function,id,status,pid,menu_name,displayorder,type',$order);
		}
		$user_role=$this->request->param();
		$where_user[]=array(
			"p.status","=",1
		);
		$where_user[]=array(
			"p.role_id","=",$user_role['role_id']
		);
		//2.拿 取用户自己的菜单
		$user_menu=$rolePermissionObj->selectRoleMenuPermission($where_user);
		//3.把用户已有的进行选中 
		foreach($manager_menu as $k=>$v){
			$manager_menu[$k]['check']=false;
			if(!empty($user_menu)){
				foreach($user_menu as $ka=>$kv){
					if($v['id']==$kv['id']){
						$manager_menu[$k]['check']=true;
					}
				}
			}
		}
		//4. 利用公用方法把菜单进行组合
		$menuPermission=new PermissionModel();
    	//$menuTag=$menuPermission->selectMenuPermission(['status'=>1],'*','id asc');
    	$menuTag=self::$model->selectMenu(['status'=>1],'*','id asc');
    	$menu=common::combination($manager_menu,$menuTag);
    	$data=common::formatList($menu);
    	return $data;
 	}

}
?>